package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
@Api(tags = "菜品相关接口")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    //清除dishCache名称下,所有的缓存数据
    @CacheEvict(value = "dishCache", allEntries = true)
    @ApiOperation(value = "新增菜品接口")
    public R saveDish(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功!");
    }

    /**
     * 菜品管理中 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "菜品分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
            @ApiImplicitParam(name = "name",value = "菜品名称",required = false)
    })
    public R<Page> pageQuery(Integer page, Integer pageSize, String name) {
        //创建page对象，设置当前页和每页大小
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //封装查询条件 where name like '%%'
        //条件构造器
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        dishQueryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        //封装排序条件
        dishQueryWrapper.orderByDesc(Dish::getCreateTime);
        //分页查询
        dishService.page(pageInfo, dishQueryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        // records: List<Dish>
        // 只有菜品分类id：categoryId，没有分类名称
        // 根据菜品分类id，查询菜品分类数据。在set进去
        // List<Dish> records ---> List<DishDto> dishDtos
        //查询列表数据
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            //分类id
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(pageInfo);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询菜品信息,用于回显")
    public R<DishDto> getByIdWithFlavor(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品信息和对应的口味信息
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    //清除dishCache名称下,所有的缓存数据
    @CacheEvict(value = "dishCache", allEntries = true)
    @ApiOperation(value = "修改菜品接口")
    public R update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFalvor(dishDto);
        return R.success("修改菜品成功!");
    }

    /**
     * 删除与批量删除菜品信息(共用)
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    //清除dishCache名称下,所有的缓存数据
    @CacheEvict(value = "dishCache", allEntries = true)
    @ApiOperation(value = "删除菜品接口")
    public R deleteDish(@RequestParam List<Long> ids) {
        //1.先删除菜品对应的口味  delete from dish_flavor where dish_id in (1,2,3)
        LambdaQueryWrapper<DishFlavor> dishFlavorQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorQueryWrapper.in(DishFlavor::getDishId, ids);
        dishFlavorService.remove(dishFlavorQueryWrapper);
        //2.再删除菜品
        dishService.removeByIds(ids);
        // TODO 使用mybatis-plus提供的逻辑删除
        return R.success("删除成功!");
    }


    /**
     * 修改菜品状态（起售/停售）
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    //清除dishCache名称下,所有的缓存数据
    @CacheEvict(value = "dishCache", allEntries = true)
    @ApiOperation(value = "起售/停售 批量起售/批量停售")
    public R updateStatus(@PathVariable Integer status,
                          @RequestParam List<Long> ids) {
        // update dish set status = ? where id in (1,2,3)
        // 方法一
        LambdaUpdateWrapper<Dish> dishUpdateWrapper = new LambdaUpdateWrapper<>();
        dishUpdateWrapper.in(Dish::getId, ids);
        dishUpdateWrapper.set(Dish::getStatus, status);
        dishService.update(dishUpdateWrapper);
        // 方法二
        /*for (Long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }*/
        // TODO update dish set status
        return R.success("修改成功!");
    }

    /**
     * 套餐管理中 添加菜品时根据分类id查询该分类下的所有菜品集合
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    // 将菜品分类ID和菜品状态组合起来作为key
    //dish_1397844391040167938_1
    @Cacheable(value = "dishCache",key = "#dish.categoryId + '_' + #dish.status")
    @ApiOperation(value = "根据分类id查询该分类下的所有菜品集合")
    public R<List<DishDto>> list(Dish dish) {
        //根据菜品分类categoryId进行查询，并且限定菜品状态为起售状态(status为1)，对查询的结果进行排序
        // 构造查询条件
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //查询条件: status = 1 ----起售状态的菜品
        dishQueryWrapper.eq(Dish::getStatus, 1);
        //排序条件 sort顺序 ,updatetime 倒序
        dishQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(dishQueryWrapper);


        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //将dish 的属性值拷贝给dishDto
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, dishId);
            //select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        /*// List<Dish> --> List<DishDto.
        List<DishDto> dishDtoList = new ArrayList<>();
        //遍历List<Dish> 集合,获取每一个Dish 对象,转变为DishDto对象,放入到新的集合List<DishDto>
        for (Dish dishes : list) {
            DishDto dishDto = new DishDto();
            //1.将dish 的属性值拷贝给dishDto
            BeanUtils.copyProperties(dishes, dishDto);
            //2.查询菜品的口味数据
            // select * from dish_flavor where dish_id = ?
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
            //3. 将菜品口味列表set 给 dishDto
            dishDto.setFlavors(flavors);
            //4. 将dishDto 放入 dishDtos 集合中
            dishDtoList.add(dishDto);
        }*/

        return R.success(dishDtoList);
    }
}
